package com.sc.common.controller;

import com.sc.common.pojo.LoginType;
import com.sc.common.pojo.Student;
import com.sc.common.service.StudentService;
import com.sc.common.shiro.token.PersonalUsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/student")
public class StudentController {
    private String loginType = LoginType.STUDENT.getLoginType();

    @Autowired
    StudentService ss;


    @RequestMapping("/login")
    public String login(String username, String password, String loginType) {
        String mess = null;
        Subject subject = SecurityUtils.getSubject();
        PersonalUsernamePasswordToken token = new PersonalUsernamePasswordToken(username, password, loginType);
        try {
            subject.login(token);
            return "show";
        } catch (UnknownAccountException e) {
            mess = "用户名不存在";
        } catch (IncorrectCredentialsException e) {
            mess = "密码输入错误";
        } catch (LockedAccountException e) {
            mess = "用户名已经冻结";
        } catch (AuthenticationException e) {
            mess = "用户名密码输入错误";
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("/register")
    public String register(Student student) {
        SimpleHash hash = new SimpleHash("MD5", student.getPassword(), student.getUsername(), 1024);
        student.setPassword(hash.toString());
        ss.insert(student);
        return "forward:/WEB-INF/js/login.jsp?loginType=student";
    }


}
